// app/service/user.js

const Service = require('egg').Service;
const bcrypt = require('bcryptjs');

class UserService extends Service {
  async registration({username, password, email}) {
    const { ctx } = this
    // 检查邮箱是否已经被使用
    const currentUser = await ctx.model.User.findOne({ email });
    if (currentUser) {
      ctx.throw(ctx.errorMap.emailExists.code, ctx.errorMap.emailExists.message);
    }
     // 加密用户密码
    const salt = await bcrypt.genSalt(10);
    password = await bcrypt.hash(password, salt);
    const user = await ctx.model.User.create({ username, password, email });
    return user ? user.toObject() : user;
  }
  async login({username = '', password = ''}) {
    // 如果是查询用户名和密码是否匹配的登录接口，那么如果查询到多个匹配的用户，通常只会返回其中的一个用户信息，
    // 而不会将所有匹配的用户信息都返回给客户端。这样可以避免数据泄露和安全问题。
    const user = await this.ctx.model.User.findOne({ username })
    // 将 Mongoose Document 对象转换为普通的 JavaScript 对象
    return user ? user.toObject() : user;
  }
  async getCurregntUser() {
    const { ctx } = this
    console.log('user1', ctx.state.user)
    let { username } = ctx.state.user
    const user = await this.ctx.model.User.findOne({ username })
    // 将 Mongoose Document 对象转换为普通的 JavaScript 对象
    return user ? user.toObject() : user;
  }
  async updateUser() {
    const { ctx } = this
    let { username } = ctx.state.user
    // const user = await this.ctx.model.User.findOne({ username })
    const { user } = ctx.request.body;
    let { email, bio, image } = user
    const userData = await ctx.model.User.updateOne({ username: username }, { email, bio, image });
     
    console.log(userData)
    return userData
  }

  async getProfile() {
    const { ctx } = this
    const { username } = ctx.params;
    const profile = await ctx.model.User.findOne({ username }).select({ email: 1, bio: 1, image: 1, _id: 0 });
    return profile ? profile.toObject() : profile;
  }
  async followUser() {
    const { ctx } = this
    console.log('floow11', ctx.state.user)
    // 查询要关注的用户的信息，例如：
    const userToFollow  = await ctx.model.User.findOne({ username: ctx.params.username });
    // 查询当前登录用户的信息，例如：
    const currentUser  = await ctx.model.User.findOne({ username: ctx.state.user.username });
    // 避免重复关注
    console.log(currentUser.following)
    console.log(userToFollow._id)
    if (!userToFollow.following.includes(currentUser._id)) {
      console.log('aa')
      // 要使用mongoose.Types.ObjectId(id) ，否则会出现如下报错
      // Cast to ObjectId failed for value \"zhangsan\" (type string) at path \"_id\" for model \"User\
      // 将要关注的用户的 ID 添加到当前登录用户的 following 数组中，
      userToFollow.following.push(ctx.app.mongoose.Types.ObjectId(currentUser._id));
      const updatedUser = await userToFollow.save();
      // console.log('updatedUser', updatedUser)
      return updatedUser ? updatedUser.toObject() : updatedUser;
    } else {
      console.log('bb')
      ctx.throw(ctx.errorMap.hadFollowed.code, ctx.errorMap.hadFollowed.message);
    }
  }
  async unfollowUser() {
    const { ctx } = this
    console.log('floow11', ctx.state.user, ctx.app.mongoose)
    const currentUser  = await ctx.model.User.findOne({ username: ctx.state.user.username });

    const userToFollow  = await ctx.model.User.findOne({ username: ctx.params.username });
    const updatedUser = await userToFollow.updateOne({ $pull: { following: ctx.app.mongoose.Types.ObjectId(currentUser._id) } });
    console.log('updatedUser2', updatedUser)
    return updatedUser
  }
}

module.exports = UserService;